package com.hualian.coupon.controller;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hualian.coupon.exception.BusinessException;
import com.hualian.coupon.pojo.Member;
import com.hualian.coupon.service.MemberService;
import com.hualian.coupon.util.JsonResult;
import com.hualian.coupon.util.ResultCode;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author Lxd
 * @Description TODO
 * @date 2020/10/22 16:38
 * @Version 1.0
 */

@RestController
@RequestMapping("/sms")
public class SMSController {

    @Resource
    MemberService memberService;

    @Resource
    RedisTemplate<String ,Object> redisTemplate;


    @RequestMapping("/send")
    public String send(@RequestParam String phone) {
        Member byPhone = memberService.findByPhone(phone);
        if (byPhone != null) {
            throw new BusinessException("该手机号已注册,请更换手机号或直接登录");
        } else {
            DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou",
                    "LTAI4GJoykh1SvFEwgeNtWBv", "ZyFFkvM4k4TbexH4EZmkpuPDUGkeA6");
            IAcsClient client = new DefaultAcsClient(profile);

            CommonRequest request = new CommonRequest();
            request.setSysMethod(MethodType.POST);
            request.setSysDomain("dysmsapi.aliyuncs.com");
            request.setSysVersion("2017-05-25");
            request.setSysAction("SendSms");
            request.putQueryParameter("RegionId", "cn-hangzhou");
            request.putQueryParameter("PhoneNumbers", phone);
            request.putQueryParameter("SignName", "ABC商城");
            request.putQueryParameter("TemplateCode", "SMS_205070808");

            //生成4位随机数验证码(1-9)
            StringBuilder code= new StringBuilder();
            for (int i=0;i<4;i++){
                code.append((int) (Math.random() * 9 + 1));
            }
            // 给阿里云短信模板中的${code}赋值，json格式
            request.putQueryParameter("TemplateParam", "{'code':"+code+"}");
            try {
                CommonResponse response = client.getCommonResponse(request);
                // 获取的验证码数据,
                String data = response.getData();
                //{"Message":"OK","RequestId":"CBC83055-A113-483A-91B2-0E4C56CCC643","BizId":"790710603115763709^0","Code":"OK"}

                ObjectMapper mapper = new ObjectMapper();
                Map<String, Object> tmpMap=mapper.readValue(data, Map.class);
                if("OK".equals(tmpMap.get("Code"))){
                    // 将数据保存在redis服务器上, 15分钟有效
                    ValueOperations<String, Object> operations = redisTemplate.opsForValue();
                    // 生成一个用手机号作为key的string,设置生存时间
                    operations.set("sms:"+phone, code.toString(),15, TimeUnit.MINUTES);

                }else{
                    throw new BusinessException(0,"验证码发送失败,请检查手机号或稍后再试");
                }


            } catch (ClientException | JsonProcessingException e) {
                e.printStackTrace();
            }
        }
        return "短信发送成功";
    }
}
